<?php

class Admin_ShowsController extends Zend_Controller_Action {

    // Mang tham so nhan duoc o moi Action
    protected $_arrParam;
    // Duong dan cua Action chinh
    protected $_actionMain;
    //thu muc upload anh
    protected $_dir_upload;

    public function init() {
        // Mang tham so nhan duoc o moi Action
        $this->_arrParam = $this->_request->getParams();
        $this->_dir_upload = UPLOAD_PATH . '/images';
        //check permissions
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $group_id = $identity->group;
        $groupsModel = new Admin_Model_Groups();
        $group_info = $groupsModel->fetchRow('id=' . $group_id)->toArray();
        $permissions = unserialize($group_info['permissions']);
        //if (!$group_info['admin'] || (!in_array($this->_arrParam ['action'], $permissions[ucfirst($this->_arrParam ['controller'])]) && $this->_arrParam ['action'] != 'index')) {
        //$this->_redirect('access_denied');
        //die();
        //}
        // Duong dan cua Action chinh        
        $this->_actionMain = '/' . $this->_arrParam ['module'] . '/' . $this->_arrParam ['controller'] . '/dashboard';
    }

    /**
     * function Index
     */
    public function indexAction() {
        $this->_redirect($this->_actionMain);
    }

    public function dashboardAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_SHOWS_INDEX");
        $this->view->headTitle($this->view->title);
        $postsModel = new Admin_Model_Posts();
        if ($this->_request->isPost()) {
            $item = $this->_arrParam ['item'];
            foreach ($item as $k => $v) {
                if ($v == '' || $v < 0) {
                    $v = 0;
                }
                if ($v > 999999) {
                    $v = 999999;
                }
                $postsModel->update(array('post_order' => $v), array('id=' . $k));
            }
        }
        $list_shows = $postsModel->fetchAll(array('post_type="shows"'));
        $paginator = Zend_Paginator::factory($list_shows);
        $paginator->setItemCountPerPage(NUM_PER_PAGE);
        $paginator->setCurrentPageNumber($this->_page);
        $this->view->list_menu = $list_shows;
        $this->view->paginator = $paginator;
    }

    public function insertAction() {
        $messages = array();
        $available_types = array(1, 2);
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_SHOWS_INSERT");
        $this->view->headTitle($this->view->title);
        $postsModel = new Admin_Model_Posts();
        $type_show = $this->_getParam('type', 0);
        if ($this->_request->isPost()) {
            if (!$_POST['post_choosetype']) {
                //echo '<pre>';
                //Zend_Debug::dump($_POST);
                //echo '</pre>';
                $upload = new Zend_File_Transfer_Adapter_Http();
                $upload->setDestination($this->_dir_upload);
                $upload->addValidator('Count', false, array(
                            'min' => 1,
                            'max' => 1
                        ))
                        ->addValidator('Size', false, array(
                            'min' => 20,
                            'max' => 10485760
                        ))
                        ->addValidator('Extension', false, 'jpg,png,gif');

                $auth = Zend_Auth::getInstance();
                $identity = $auth->getIdentity();

                $post_title = trim($_POST['post_title']);
                $post_content = trim($_POST['post_content']);
                $post_parent = trim($_POST['post_parent']);
                $post_status = $_POST['post_status'];
                $post_order = trim($_POST['post_order']);
                $post_author = $identity->id;
                $post = array(
                    'post_status' => $post_status,
                    'post_title' => $post_title,
                    'post_content' => $post_content,
                    'post_author' => $post_author,
                    'post_order' => (int) $post_order,
                    'post_parent' => (int) $post_parent,
                    'post_type' => 'shows'
                );
                $post_id = $postsModel->insertPost($post);
                $postMetaModel = new Admin_Model_PostsMeta();

                $meta_show_date_start = trim($_POST['show_date_start']);
                $meta_show_date_start_sell = trim($_POST['show_date_start_sell']);
                $meta_show_date_end_sell = trim($_POST['show_date_end_sell']);
                $meta_show_max_buy_ticket = trim($_POST['show_max_buy_ticket']);
                $meta_show_address = trim($_POST['show_address']);
                $meta_show_google_map = trim($_POST['show_google_map']);
                $meta_show_partner = trim($_POST['show_partner']);
                $meta_show_type = trim($_POST['show_type']);

                $data_meta_date_start = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_date_start',
                    'meta_value' => $meta_show_date_start
                );
                $postMetaModel->insert($data_meta_date_start);

                $data_meta_date_start_sell = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_date_start_sell',
                    'meta_value' => $meta_show_date_start_sell
                );
                $postMetaModel->insert($data_meta_date_start_sell);

                $data_meta_date_end_sell = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_date_end_sell',
                    'meta_value' => $meta_show_date_end_sell
                );
                $postMetaModel->insert($data_meta_date_end_sell);

                $data_meta_max_buy_ticket = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_max_buy_ticket',
                    'meta_value' => $meta_show_max_buy_ticket
                );
                $postMetaModel->insert($data_meta_max_buy_ticket);

                $data_meta_address = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_address',
                    'meta_value' => $meta_show_address
                );
                $postMetaModel->insert($data_meta_address);

                $data_meta_google_map = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_google_map',
                    'meta_value' => $meta_show_google_map
                );
                $postMetaModel->insert($data_meta_google_map);

                $data_meta_partner = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_partner',
                    'meta_value' => $meta_show_partner
                );
                $postMetaModel->insert($data_meta_partner);

                $data_meta_type = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_type',
                    'meta_value' => $meta_show_type
                );
                $postMetaModel->insert($data_meta_type);

                if ($upload->isValid()) {
                    $files = $upload->getFileInfo();
                    foreach ($files as $file => $info) {
                        if ($info['name'] != '') {
                            $validator = new Zend_Validate_File_Exists($this->_dir_upload);
                            if ($validator->isValid($info['name'])) {
                                $file_name = $upload->getFileName($info['name']);
                                preg_match("/\.([^\.]+)$/", $file_name, $matches);
                                $file_ext = $matches[1];
                                $file_name = time() . '.' . $file_ext;
                                $arrFileName[$file] = $file_name;
                                $upload->addFilter('Rename', $this->_dir_upload . '/' . $file_name);
                            } else {
                                $arrFileName[$file] = $info['name'];
                            }
                            $upload->receive($file);
                        }
                    }
                    //EOB: save file to server	 
                    $data_meta_image = array(
                        'post_id' => $post_id,
                        'meta_key' => 'show_images',
                        'meta_value' => $arrFileName['show_image']
                    );
                    $postMetaModel->insert($data_meta_image);
                }

                $meta_show_stands = $_POST['show_stands'];
                $meta_quantity_ticket = $_POST['show_quantity_ticket'];
                $meta_price_display = $_POST['show_price_display'];
                $meta_price_sell = $_POST['show_price_sell'];

                $stand_all_values = array();
                foreach ($meta_show_stands as $stand_key => $stand_id) {
                    $stand_values = array(
                        'show_quantity_ticket' => $meta_quantity_ticket[$stand_key],
                        'show_price_display' => $meta_price_display[$stand_key],
                        'show_price_sell' => $meta_price_sell[$stand_key]
                    );
                    $stand_all_values[$stand_id] = $stand_values;
                }

                $data_meta_stands = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_stands',
                    'meta_value' => serialize($stand_all_values)
                );
                $postMetaModel->insert($data_meta_stands);

                $messages [] = array(
                    'text' => $translate->_("ADMIN_TEXT_MESSAGE_ADD_SHOWS_SUCCESS"),
                    'type' => 'success'
                );
            } else {
                $this->_redirect('/' . $this->_arrParam ['module'] . '/' . $this->_arrParam ['controller'] . '/' . $this->_arrParam ['action'] . '/type/' . $_POST['post_type']);
            }
        }
        if (!in_array($type_show, $available_types)) {
            $form = new Admin_Form_Shows_ChooseType();
            $this->view->form = $form;
        } else {
            //List Stands
            $list_stands = $postsModel->fetchAll(array('post_type="stands"'))->toArray();
            $options_stands = array();
            foreach ($list_stands as $stands) {
                $options_stands[$stands['id']] = $stands['post_title'];
            }
            //List Partners
            $list_partners = $postsModel->fetchAll(array('post_type="partner"', 'post_status=1'))->toArray();
            $options_partner = array();
            foreach ($list_partners as $partner) {
                $options_partner[$partner['id']] = $partner['post_title'];
            }
            //List menu
            $list_menu = Array();
            $top_menu = $postsModel->fetchAll(array('post_type="menu"', 'post_parent=0', 'post_status=1'), 'post_order ASC')->toArray();
            if (sizeof($top_menu) > 0) {
                foreach ($top_menu as $menu) {
                    $list_menu [$menu['id']] = $menu['post_title'];
                    $sub_menu = $postsModel->fetchAll(array('post_type="menu"', 'post_parent=' . $menu ['id']), 'post_order ASC')->toArray();
                    foreach ($sub_menu as $smenu) {
                        $list_menu [$smenu['id']] = '---' . $smenu['post_title'];
                    }
                }
            }
            $this->view->options_stands = $options_stands;
            $this->view->options_partner = $options_partner;
            $this->view->options_menu = $list_menu;
            $this->_helper->viewRenderer->setRender('inserttype' . $type_show);
        }
        $this->view->message = $messages;
    }

    public function updateAction() {
        $messages = array();
        $available_types = array(1, 2);
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_SHOWS_UPDATE");
        $this->view->headTitle($this->view->title);
        $postsModel = new Admin_Model_Posts();
        $postMetaModel = new Admin_Model_PostsMeta();
        $post_id = $this->_getParam('id', 0);

        //List Stands
        $list_stands = $postsModel->fetchAll(array('post_type="stands"'))->toArray();
        $options_stands = array();
        foreach ($list_stands as $stands) {
            $options_stands[$stands['id']] = $stands['post_title'];
        }
        //List Partners
        $list_partners = $postsModel->fetchAll(array('post_type="partner"', 'post_status=1'))->toArray();
        $options_partner = array();
        foreach ($list_partners as $partner) {
            $options_partner[$partner['id']] = $partner['post_title'];
        }
        //List menu
        $list_menu = Array();
        $top_menu = $postsModel->fetchAll(array('post_type="menu"', 'post_parent=0', 'post_status=1'), 'post_order ASC')->toArray();
        if (sizeof($top_menu) > 0) {
            foreach ($top_menu as $menu) {
                $list_menu [$menu['id']] = $menu['post_title'];
                $sub_menu = $postsModel->fetchAll(array('post_type="menu"', 'post_parent=' . $menu ['id']), 'post_order ASC')->toArray();
                foreach ($sub_menu as $smenu) {
                    $list_menu [$smenu['id']] = '---' . $smenu['post_title'];
                }
            }
        }
        $this->view->options_stands = $options_stands;
        $this->view->options_partner = $options_partner;
        $this->view->options_menu = $list_menu;

        if ($this->_request->isPost()) {
            if (!$_POST['post_choosetype']) {
                $upload = new Zend_File_Transfer_Adapter_Http();
                $upload->setDestination($this->_dir_upload);
                $upload->addValidator('Count', false, array(
                            'min' => 1,
                            'max' => 1
                        ))
                        ->addValidator('Size', false, array(
                            'min' => 20,
                            'max' => 10485760
                        ))
                        ->addValidator('Extension', false, 'jpg,png,gif');
                //get post data
                $post_title = trim($_POST['post_title']);
                $post_content = trim($_POST['post_content']);
                $post_parent = trim($_POST['post_parent']);
                $post_status = $_POST['post_status'];
                $post_order = trim($_POST['post_order']);
                $post = array(
                    'post_status' => $post_status,
                    'post_title' => $post_title,
                    'post_content' => $post_content,
                    'post_order' => (int) $post_order,
                    'post_parent' => (int) $post_parent,
                );
                //update post
                $process_upadte = $postsModel->updatePost($post_id, $post);

                //get meta post data
                $meta_show_date_start = trim($_POST['show_date_start']);
                $meta_show_date_start_sell = trim($_POST['show_date_start_sell']);
                $meta_show_date_end_sell = trim($_POST['show_date_end_sell']);
                $meta_show_max_buy_ticket = trim($_POST['show_max_buy_ticket']);
                $meta_show_address = trim($_POST['show_address']);
                $meta_show_google_map = trim($_POST['show_google_map']);
                $meta_show_partner = trim($_POST['show_partner']);
                $meta_show_type = trim($_POST['show_type']);

                $meta_show_stands = $_POST['show_stands'];
                $meta_quantity_ticket = $_POST['show_quantity_ticket'];
                $meta_price_display = $_POST['show_price_display'];
                $meta_price_sell = $_POST['show_price_sell'];

                $stand_all_values = array();
                foreach ($meta_show_stands as $stand_key => $stand_id) {
                    $stand_values = array(
                        'show_quantity_ticket' => $meta_quantity_ticket[$stand_key],
                        'show_price_display' => $meta_price_display[$stand_key],
                        'show_price_sell' => $meta_price_sell[$stand_key]
                    );
                    $stand_all_values[$stand_id] = $stand_values;
                }

                $data_meta_stands = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_stands',
                    'meta_value' => serialize($stand_all_values)
                );

                $data_meta_date_start = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_date_start',
                    'meta_value' => $meta_show_date_start
                );

                $data_meta_date_start_sell = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_date_start_sell',
                    'meta_value' => $meta_show_date_start_sell
                );

                $data_meta_date_end_sell = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_date_end_sell',
                    'meta_value' => $meta_show_date_end_sell
                );

                $data_meta_max_buy_ticket = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_max_buy_ticket',
                    'meta_value' => $meta_show_max_buy_ticket
                );

                $data_meta_address = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_address',
                    'meta_value' => $meta_show_address
                );

                $data_meta_google_map = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_google_map',
                    'meta_value' => $meta_show_google_map
                );

                $data_meta_partner = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_partner',
                    'meta_value' => $meta_show_partner
                );

                $data_meta_type = array(
                    'post_id' => $post_id,
                    'meta_key' => 'show_type',
                    'meta_value' => $meta_show_type
                );

                $all_meta = array(
                    $data_meta_stands,
                    $data_meta_date_start,
                    $data_meta_date_start_sell,
                    $data_meta_date_end_sell,
                    $data_meta_max_buy_ticket,
                    $data_meta_address,
                    $data_meta_google_map,
                    $data_meta_partner,
                    $data_meta_type
                );

                if ($upload->isValid()) {
                    $files = $upload->getFileInfo();
                    foreach ($files as $file => $info) {
                        if ($info['name'] != '') {
                            $validator = new Zend_Validate_File_Exists($this->_dir_upload);
                            if ($validator->isValid($info['name'])) {
                                $file_name = $upload->getFileName($info['name']);
                                preg_match("/\.([^\.]+)$/", $file_name, $matches);
                                $file_ext = $matches[1];
                                $file_name = time() . '.' . $file_ext;
                                $arrFileName[$file] = $file_name;
                                $upload->addFilter('Rename', $this->_dir_upload . '/' . $file_name);
                            } else {
                                $arrFileName[$file] = $info['name'];
                            }
                            $upload->receive($file);
                        }
                    }
                    //EOB: save file to server	 
                    $data_meta_image = array(
                        'post_id' => $post_id,
                        'meta_key' => 'show_images',
                        'meta_value' => $arrFileName['show_image']
                    );
                    $all_meta[] = $data_meta_image;
                }

                foreach ($all_meta as $meta) {
                    $check_meta_exits = $postMetaModel->fetchRow(array('post_id=' . $post_id, 'meta_key="' . $meta['meta_key'] . '"'));
                    if ($check_meta_exits) {
                        $postMetaModel->update($meta, array('post_id=' . $post_id, 'meta_key="' . $meta['meta_key'] . '"'));
                    } else {
                        $postMetaModel->insert($meta);
                    }
                }

                if ($process_upadte) {
                    $messages [] = array(
                        'text' => $translate->_("ADMIN_TEXT_MESSAGE_UPDATE_SHOWS_SUCCESS"),
                        'type' => 'success'
                    );
                }else{
                    $messages [] = array(
                    'text' => $translate->_("ADMIN_TEXT_MESSAGE_UPDATE_SHOWS_FAILD"),
                    'type' => 'errormsg'
                );
                }
            } else {
                $messages [] = array(
                    'text' => $translate->_("ADMIN_TEXT_MESSAGE_UPDATE_SHOWS_FAILD"),
                    'type' => 'errormsg'
                );
            }
        }

        $data = $postsModel->fetchRow('id=' . $post_id)->toArray();
        $data_meta = $postMetaModel->fetchAll('post_id=' . $post_id)->toArray();

        $meta_filter_key = array();
        foreach ($data_meta as $meta) {
            $meta_filter_key[$meta['meta_key']] = $meta['meta_value'];
        }

        if (!$meta_filter_key['show_type'] || !in_array($meta_filter_key['show_type'], $available_types)) {
            $messages [] = array(
                'text' => $translate->_("ADMIN_TEXT_MESSAGE_UPDATE_SHOW_NOT_FOUND_DATA"),
                'type' => 'errormsg'
            );
        } else {
            $this->_helper->viewRenderer->setRender('updatetype' . $meta_filter_key['show_type']);
        }

        $this->view->data = $data;
        $this->view->data_meta = $meta_filter_key;
        $this->view->message = $messages;
    }

    public function deleteitemsAction() {
        $this->_helper->layout()->disableLayout();
        $postsModel = new Admin_Model_Posts();
        if ($this->_request->isPost()) {
            $item = $this->_arrParam ['cid'];
            foreach ($item as $k => $v) {
                $postsModel->delete(array('id=' . $v));
            }
        }
        $this->_redirect($this->_actionMain);
    }

    public function activeAction() {
        $this->_helper->layout()->disableLayout();
        $type = $this->_request->getParam('type', 1);
        $id = $this->_request->getParam('id', 0);

        if ($type > 0) {
            $type = 1;
        } else {
            $type = 0;
        }

        $postsModel = new Admin_Model_Posts();
        $data = array('post_status' => $type);
        $postsModel->updatePost($id, $data);
        $this->_redirect($this->_actionMain);
    }
    
    public function deleteAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_SHOWS_DELETE");
        $this->view->headTitle($this->view->title);

        $id = $this->_getParam('id', 0);
        $postsModel = new Admin_Model_Posts();
        if ($this->getRequest()->isPost()) {
            $del = $this->getRequest()->getPost('del');
            if ($del == 'Yes') {
                $process = $postsModel->delete(array('id=' . $id));
            }
            $this->_redirect($this->_actionMain);
        } else {
            $post = $postsModel->fetchRow('id=' . $id)->toArray();
            $this->view->post = $post;
        }
    }
    
}